const { getMyself } = require('../../utils/request');

Page({
  data: {
    username: '',
    password: '',
    loading: false
  },

  // 输入框变化处理
  handleInputChange(e) {
    const { field } = e.currentTarget.dataset;
    this.setData({
      [field]: e.detail.value
    });
  },

  // 登录处理
  async handleLogin(e) {
    const { username, password: accessToken } = e.detail.value;
    
    if (!username.trim()) {
      wx.showToast({ title: '请输入用户名', icon: 'none' });
      return;
    }
    
    if (!accessToken.trim()) {
      wx.showToast({ title: '请输入Access Token', icon: 'none' });
      return;
    }
    
    this.setData({ loading: true });
    
    try {
      // 临时替换全局的ACCESS_TOKEN
      getApp().globalData.accessToken = accessToken;
      
      // 测试Token是否有效
      const userInfo = await getMyself();
      
      if (userInfo && userInfo.id) {
        // 登录成功，保存用户信息
        wx.setStorageSync('isLogin', true);
        wx.setStorageSync('userInfo', userInfo);
        wx.setStorageSync('username', username);
        wx.setStorageSync('accessToken', accessToken);
        
        wx.showToast({ title: '登录成功' });
        setTimeout(() => {
          wx.switchTab({ url: '/pages/index/index' });
        }, 1500);
      } else {
        throw new Error('Access Token无效');
      }
    } catch (error) {
      console.error('登录失败:', error);
      wx.showToast({ title: error.message || '登录失败', icon: 'none' });
      // 恢复全局ACCESS_TOKEN
      getApp().globalData.accessToken = '';
    } finally {
      this.setData({ loading: false });
    }
  },


  // 生命周期函数
  onLoad() {
    // 检查是否已登录
    if (wx.getStorageSync('isLogin')) {
      wx.switchTab({
        url: '/pages/index/index'
      });
    }
  }
});